<template>
    <div>
        <!-- 新增/编辑SKU - SkuForm
        <el-button @click="emit('update:modelValue', STATUS.SPULIST)">取消</el-button> -->

        <el-form label-width="100px">
            <el-form-item label="SPU名称">
                小米666
            </el-form-item>

            <el-form-item label="SKU名称">
                <el-input v-model="skuForm.skuName" placeholder="SKU名称"></el-input>
            </el-form-item>

            <el-form-item label="价格(元)">
                <el-input v-model="skuForm.price" type="number" placeholder="价格(元)"></el-input>
            </el-form-item>

            <el-form-item label="重量(千克)">
                <el-input v-model="skuForm.weight" type="number" placeholder="重量(千克)"></el-input>
            </el-form-item>

            <el-form-item label="规格描述">
                <el-input v-model="skuForm.skuDesc" type="textarea" :rows="3" placeholder="规格描述"></el-input>
            </el-form-item>

            <el-form-item label="平台属性">
                <el-form :inline="true">
                    <el-form-item :label="attr.attrName" v-for="attr in attrList" :key="attr.id">
                        <el-select v-model="attr.attrIdvalId" placeholder="请选择">
                            <el-option v-for="attrVal in attr.attrValueList" :key="attrVal.id"
                                :label="attrVal.valueName" :value="`${attr.id}:${attrVal.id}`"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </el-form-item>

            <el-form-item label="销售属性">
                <el-form :inline="true">
                    <el-form-item :label="saleAttr.saleAttrName" v-for="saleAttr in saleAttrList" :key="saleAttr.id">
                        <el-select v-model="saleAttr.attrIdvalId" placeholder="请选择">
                            <el-option v-for="saleAttrVal in saleAttr.spuSaleAttrValueList" :key="saleAttrVal.id"
                                :label="saleAttrVal.saleAttrValueName"
                                :value="`${saleAttr.id}:${saleAttrVal.id}`"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </el-form-item>

            <el-form-item label="图片列表">
                <el-table :data="spuImageList" border @selection-change="selectionChange" size="small">
                    <el-table-column type="selection" width="80" align="center"></el-table-column>
                    <el-table-column label="图片">
                        <template #default="{ row, $index }">
                            <img :src="row.imgUrl" style="width: 60px;height: 60px;">
                        </template>
                    </el-table-column>
                    <el-table-column label="名称" prop="imgName"></el-table-column>
                    <el-table-column label="操作" width="120">
                        <template #default="{ row, $index }">
                            <el-tag type="success" v-if="row.isDefault == '1'">默认</el-tag>
                            <el-button v-else type="primary" size="small" @click="setDetaultImage(row)">设置默认</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="onSave">保存</el-button>
                <el-button @click="cancelSave">取消</el-button>
            </el-form-item>

        </el-form>

    </div>
</template>
  
<script setup lang="ts">
import skuApi, { type SkuModel } from '@/api/sku';
import attrApi, { type AttrModel } from '@/api/attr'
import spuApi, { type SpuModel, type SpuSaleAttrModel, type SpuImageModel } from '@/api/spu'
import { ElMessage } from 'element-plus';
import { onMounted, ref } from 'vue';
import { STATUS } from '../../index.vue'
import useCategoryStore from '@/stores/category';
const categoryStore = useCategoryStore()

const porps = defineProps<{
    modelValue: number,
    spuInfo: SpuModel
}>()

const emit = defineEmits<{
    (e: 'update:modelValue', status: number): void,
    (e: 'changeSpuInfo'): void
}>()

const onSave = async () => {
    // 组装数据
    // 组装平台属性数据
    skuForm.value.skuAttrValueList = attrList.value.filter(item => item.attrIdvalId).map(item => {
        const [attrId, valueId] = (item.attrIdvalId as string).split(':'); // "属性id:属性值id"
        return {
            attrId,
            valueId
        }
    })
    // 组装销售属性
    skuForm.value.skuSaleAttrValueList = saleAttrList.value.filter(item => item.attrIdvalId).map(item => {
        const [saleAttrId, saleAttrValueId] = item.attrIdvalId!.split(':');
        return {
            saleAttrId,
            saleAttrValueId
        }
    })
    // 默认图片
    skuForm.value.skuDefaultImg = (spuImageList.value.find(item => item.isDefault == '1')||{}).imgUrl!
    // 图片列表已经筹集完毕
    skuForm.value.spuId = porps.spuInfo.id;
    skuForm.value.tmId = porps.spuInfo.tmId;
    skuForm.value.category3Id = categoryStore.category3Id;
    // price,skuName,skuDesc,weight  v-model 收集

    // 调用接口
    try {
        await skuApi.save(skuForm.value);

        ElMessage.success('保存成功')

        cancelSave(); // 切换主界面
    } catch (error) {
        ElMessage.error('保存失败,请重试')
    }
}

const cancelSave = () => {
    emit('update:modelValue', STATUS.SPULIST); // 切换主列表
    // 同时需要初始化一下 父组件的spuInfo,防止再次新增 spu 会把 spuInfo 的数据传入 spuForm
    emit('changeSpuInfo')
}


// 图片表格选中的回调
const selectionChange = (val: SpuImageModel[]) => {
    skuForm.value.skuImageList = val;
}
// 设置默认图片
const setDetaultImage = (row: SpuImageModel) => {
    spuImageList.value.forEach(item => item.isDefault = '0')
    row.isDefault = '1'
}

const initSkuForm = (): SkuModel => ({
    spuId: undefined,
    price: undefined,
    skuName: '',
    skuDesc: '',
    weight: '',
    tmId: undefined,
    category3Id: undefined, // 保存的时候收集
    skuDefaultImg: '',
    createTime: '', // 不管
    skuImageList: [],
    skuAttrValueList: [],
    skuSaleAttrValueList: []
})
// 收集数据
const skuForm = ref<SkuModel>(initSkuForm())






















// 获取平台属性
const attrList = ref<AttrModel[]>([])
const getAttrList = async () => {
    try {
        const { category1Id, category2Id, category3Id } = categoryStore
        let result = await attrApi.attrInfoList(category1Id!, category2Id!, category3Id!)
        attrList.value = result
    } catch (error) {
        ElMessage.error('获取平台属性失败，请重试')
    }
}

// 获取销售属性列表
const saleAttrList = ref<SpuSaleAttrModel[]>([])
const getSaleAttrListBySpuId = async () => {
    try {
        let result = await spuApi.getSpuSaleAttrListBySpuId(porps.spuInfo.id!)
        saleAttrList.value = result
    } catch (error) {
        ElMessage.error('获取销售属性失败，请重试')
    }
}

// 获取图片列表数据
const spuImageList = ref<SpuImageModel[]>([])
const getSpuImageListBySpuId = async () => {
    try {
        let result = await spuApi.getSpuImageLIstBySpuId(porps.spuInfo.id!)
        spuImageList.value = result
    } catch (error) {
        ElMessage.error('获取图片列表失败，请重试')
    }
}

// 初始化数据
const initData = () => {
    getAttrList();// 获取平台属性
    getSaleAttrListBySpuId();// 获取销售属性列表
    getSpuImageListBySpuId();// 获取图片列表数据
}


onMounted(() => {
    initData()
})

</script>
  
<style scoped>

</style>